package model;

import java.io.File;

import weka.core.Instance;
import weka.core.Instances;

public class WavToInstanceParser extends WavParser {

	private static Instance instance = null;

	public static Instance parseToInstance(String absoluteFileName,
			Instances instances, boolean fromStart, int offset) {
		File[] fToParse = getFiles(absoluteFileName, WAV_EXTENSION);
		double[][] coeffs = getCoefficients(fToParse[0].getAbsolutePath());
		int instanceSize = instances.numAttributes();
		instance = new Instance(instanceSize);
		instance.setDataset(instances);
		instance = readFromEnd(instances, coeffs, instance, offset);

		return instance;

	}

	@SuppressWarnings("unused")
	private static Instance readFromStart(Instances instances,
			double[][] coeffs, Instance instance) {
		int instanceSize = instances.numAttributes() - 1;
		for (int i = 0; i < instanceSize; i++) {
			String[] attrIndexes = instances.attribute(i).name().split("_");
			int x = Integer.parseInt(attrIndexes[0]);
			int y = Integer.parseInt(attrIndexes[1]);
			if (x >= coeffs.length || y >= coeffs[0].length) {
				instance.setValue(i, MISSING_VALUE);
			} else {
				instance.setValue(i, coeffs[x][y]);
			}
		}
		return instance;
	}

	private static Instance readFromEnd(Instances instances, double[][] coeffs,
			Instance instance, int offset) {
		int instanceSize = instances.numAttributes() - 1;
		for (int i = 0; i < instanceSize; i++) {
			String[] attrIndexes = instances.attribute(i).name().split("_");
			int x = Integer.parseInt(attrIndexes[0]);
			int y = Integer.parseInt(attrIndexes[1]);
			if (x + offset >= coeffs.length || y >= coeffs[0].length) {
				instance.setValue(i, MISSING_VALUE);
			} else {
				instance.setValue(i, coeffs[x + offset][y]);
			}
		}
		return instance;
	}

}
